package com.a.module_map;

import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.widget.*;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.myprint.ui.MyDialog;
import com.a.lib_base.BaseApp;
import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.param.DrivingParam;
import com.tencent.lbssearch.object.result.DrivingResultObject;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.LocationSource;
import com.tencent.tencentmap.mapsdk.maps.MapView;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.model.*;
import com.tencent.tencentmap.mapsdk.vector.utils.animation.MarkerTranslateAnimator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MapActivity extends AppCompatActivity implements View.OnClickListener, TencentLocationListener, LocationSource, SensorEventListener {

    private static final String TAG = MapActivity.class.getSimpleName();
    private static final int GPS_REQUEST_CODE = 999;
    private MapView mapView;
    private TencentMap mMap;
    private Button orderBtn;

    private final long TIME_SENSOR = 100;
    private TencentMap tencentMap;
    private StringBuffer lineStringBuilder = new StringBuffer();

    private LatLng fromLatLng;
    private LatLng toLatLng;
    private LatLng car_Location;

    private boolean IS_SINGLE_LOCATION_MODE = false;//是否连续定位
    private TencentLocationManager mLocationManager = TencentLocationManager.getInstance(BaseApp.getContext());
    private TencentLocationRequest locationRequest;

    private TencentSearch tencentSearch = new TencentSearch(BaseApp.getContext());

    private Marker carMarker;
    private Marker pointerMarker = null;
    private LatLng[] mCarLatLngArray;
    private MarkerTranslateAnimator mAnimator;

    private SensorManager sensorManager;

    private LinearLayout ll_navigation, ll_twoBtn;
    private ImageButton imgbtn_location;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        initView();
        initData();
    }


    public void initView() {
        mapView = findViewById(R.id.mapview);
        orderBtn = findViewById(R.id.order_btn);
        ll_navigation = findViewById(R.id.ll_navigation);
        imgbtn_location = findViewById(R.id.map_imgbtn_location);
        mMap = mapView.getMap();
//        ImageView imgBack = findViewById(R.id.img_back);
//        imgBack.setOnClickListener(view -> finish());

    }


    public static void actionStart(Context context, @Nullable Integer intentFlag) {
        Intent intent = new Intent(context, MapActivity.class);
        if (intentFlag != null) {
            intent.setFlags(intentFlag);
        }
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {

    }


    private void initData() {
        tencentMap = mapView.getMap();
        //   drivingRoutePresent.geocoder("上海", DrivingRoutePresent.FROM_TYPE);
        //drivingRoutePresent.geocoder("北京", DrivingRoutePresent.TO_TYPE);
        toLatLng = new LatLng();
        startLocation(true);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取手机的传感器，方向传感器。
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_FASTEST);
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
//                while(car_Location==null)
//                {
                //一直获取“我的位置”,直到获取到
//                }
                carMarker = tencentMap.addMarker(new MarkerOptions(car_Location)
                        .title("货车1号:")
                        .anchor(0.5f, 0.5f)
                        .viewInfoWindow(true)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.cars))
                        .flat(true)
                        .clockwise(false)
                        .draggable(true));// 设置默认显示一个infowinfow
                routePlan();
            }
        });
        thread.start();

    }

    /*
       路线绘制
     */ boolean isRouteshow = false;

    public void routePlan() {
        Log.d(TAG, "RoutPlan 执行了");
        toLatLng = new LatLng();
        toLatLng.setLatitude(39.98409);
        toLatLng.setLongitude(116.30804); //北京经纬坐标
        if (fromLatLng != null && toLatLng != null) {

            isRouteshow = true;
            DrivingParam drivingParam = new DrivingParam(fromLatLng, toLatLng);// 出发点经纬度，目的地经纬度
            drivingParam.policy(DrivingParam.Policy.TRIP);//驾车路线规划策略

            //  drivingParam.setCarNumber("粤A00001");//填入车牌号，在路线规划时会避让车牌限行区域


            //开始规划路线
            tencentSearch.getRoutePlan(drivingParam, new HttpResponseListener<DrivingResultObject>() {

                @Override
                public void onSuccess(int i, DrivingResultObject drivingResultObject) {
                    List<LatLng> latLngs = null;
                    for (DrivingResultObject.Route route : drivingResultObject.result.routes) {
                        latLngs = route.polyline;
                        //  tencentMap.addPolyline(new PolylineOptions().addAll(latLngs).width(15f).color(0xFFFF0000));
                        tencentMap.addPolyline(setLineStyle(3, latLngs)); //绘制线

                        for (LatLng latLng : route.polyline) {
                            lineStringBuilder.append(latLng.latitude + "," + latLng.longitude);
                            lineStringBuilder.append(",");
                        }

                    }
                    initAnimation(lineStringBuilder.substring(0, lineStringBuilder.length() - 1));
                }

                @Override
                public void onFailure(int i, String s, Throwable throwable) {
                    Log.d("MapActivity", "OnFailure: " + s + i);
                }
            });
            //   CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(fromLatLng); //动画移动
            tencentMap.moveCamera(CameraUpdateFactory.newLatLng(fromLatLng));
            lineStringBuilder = new StringBuffer();
            addMarkers();
            fromLatLng = null;
            // toLatLng=null;
        }
    }
/*
绘制线
 */

    private PolylineOptions setLineStyle(int type, List<LatLng> latLngs) {
        PolylineOptions polylineOptions = new PolylineOptions().addAll(latLngs).lineCap(true);
        switch (type) {
            case 0:
                //设置折线颜色、宽度
                polylineOptions
                        .color(0xff00ff00)
                        .width(10f);
                break;
            case 1:
                List<Integer> list = new ArrayList<>();
                list.add(35);
                list.add(20);
                polylineOptions
                        .lineType(PolylineOptions.LineType.LINE_TYPE_IMAGEINARYLINE)
                        .width(10)
                        .pattern(list);
                break;
            case 2:
                //线路颜色值纹理图片里的颜色索引
                polylineOptions
                        .colorType(PolylineOptions.ColorType.LINE_COLOR_TEXTURE)
                        .color(PolylineOptions.Colors.GREEN)
                        .colorTexture(BitmapDescriptorFactory.fromAsset("texture_arrows.png"));
                break;
            case 3:
                polylineOptions
                        .arrow(true)
                        .arrowSpacing(100)
                        .arrowTexture(BitmapDescriptorFactory.fromAsset("texture_arrows.png"));
                break;

        }
        return polylineOptions;
    }

    /*
    添加地点的标注
     */ Marker marker1;

    private void addMarkers() {
        setInofoView(false);//设置marker得弹窗样式  //true 为货车司机信息弹窗， false为经停点信息弹窗
        tencentMap.enableMultipleInfowindow(true);
        marker1 = tencentMap.addMarker(new MarkerOptions(toLatLng)
                // .title("北京仓库")

                .anchor(0.5f, 0.5f)
                .viewInfoWindow(true)
                //   .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))//默认样式
                .icon(BitmapDescriptorFactory.fromAsset("stopoverr.png"))
                .draggable(true));// 设置默认显示一个infowinfow*/

      /*  Marker marker2 = tencentMap.addMarker(new MarkerOptions(fromLatLng)
                .title("出发点")
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                .draggable(true));*/

      /*  Marker marker3 = tencentMap.addMarker(new MarkerOptions(car_Location)
                .icon( BitmapDescriptorFactory.fromAsset("texture_arrows.png"))
                .anchor(0.5f,0.5f)
                .flat(true)
                .draggable(true));*/

        marker1.showInfoWindow();
        //  marker2.showInfoWindow();
        //   marker3.showInfoWindow();
    }

    public void startLocation(boolean single) {
        IS_SINGLE_LOCATION_MODE = single;//因为这里只需要定位一次，所以加了个参数
        locationRequest = TencentLocationRequest.create();
        locationRequest.setInterval(3000);//定位间隔
        //根据用户获取的位置信息的详细程度，REQUEST_LEVEL_ADMIN_AREA:包含经纬度，位置所处的中国大陆行政区划
        locationRequest.setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA);
        locationRequest.setAllowGPS(true);//是否允许使用GPS定位
        mLocationManager.requestLocationUpdates(locationRequest, this);//连续定位

        //地图上设置定位数据源
        tencentMap.setLocationSource(this);
        //设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        tencentMap.setMyLocationEnabled(true);

    }

    //小车按路线移动动画
    public void initAnimation(String line) {
        //拆分获得经纬度数组
        String[] linePointsStr = line.split(",");
        mCarLatLngArray = new LatLng[linePointsStr.length / 2];
        for (int i = 0; i < mCarLatLngArray.length; i++) {
            double latitude = Double.parseDouble(linePointsStr[i * 2]);
            double longitude = Double.parseDouble(linePointsStr[i * 2 + 1]);
            mCarLatLngArray[i] = new LatLng(latitude, longitude);
        }

        //添加小车路线
        mMap.addPolyline(new PolylineOptions().add(mCarLatLngArray)
                .color(R.color.red));

        //添加小车
        LatLng carLatLng = mCarLatLngArray[0];

        //创建移动动画
        mAnimator = new MarkerTranslateAnimator(carMarker, 50 * 1000, mCarLatLngArray, true);

        //调整最佳视野
        mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(
                LatLngBounds.builder().include(Arrays.asList(mCarLatLngArray)).build(), 50));
        mAnimator.startAnimation();  //动画演示
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        startLocation(true);
        //  mLocationManager = TencentLocationManager.getInstance(GlobalApplication.getContext());
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_FASTEST);
        if (!checkGPSIsOpen())
            initDialog();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();


    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();
        mLocationManager.removeUpdates(this);
        sensorManager.unregisterListener(this);//关闭传感器管理服务
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        mLocationManager.removeUpdates(this);
        sensorManager.unregisterListener(this);//关闭传感器管理服务

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mapView.onRestart();
    }

    boolean isLocation = false;
    boolean isNavigation = false;
    private OnLocationChangedListener mOnLocationChangedListener;

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {

        switch (i) {
            case TencentLocation.ERROR_OK:
                Location location = new Location(tencentLocation.getProvider());
                //设置经纬度
                location.setLatitude(tencentLocation.getLatitude());
                location.setLongitude(tencentLocation.getLongitude());
                //设置精度，这个值会被设置为定位点上表示精度的圆形半径
                location.setAccuracy(tencentLocation.getAccuracy());
                //设置定位标的旋转角度，注意 tencentLocation.getBearing() 只有在 gps 时才有可能获取
                location.setBearing((float) tencentLocation.getBearing());
                //将位置信息返回给地图
                mOnLocationChangedListener.onLocationChanged(location);
                //定位成功
                Log.d(TAG, "tencentLocation: " + tencentLocation.getAddress() + "这里经度为" + tencentLocation.getLongitude());


                car_Location = new LatLng(tencentLocation.getLatitude(), tencentLocation.getLongitude());
                if (!isRouteshow)
                    routePlan();

                fromLatLng = car_Location;

                if (isNavigation)
                    pointerMarker.setPosition(car_Location);
          /*      if(!isLocation){
                    routePlan();
                    isLocation=true;
                }*/
                //渲染定位信息
//                Toast.makeText(GlobalApplication.getContext(), "定位成功", Toast.LENGTH_SHORT).show();
                break;
            case TencentLocation.ERROR_NETWORK:
                Toast.makeText(BaseApp.getContext(), "网络问题引起的定位失败", Toast.LENGTH_SHORT).show();
                break;
            case TencentLocation.ERROR_BAD_JSON:
                Toast.makeText(BaseApp.getContext(), "GPS, Wi-Fi 或基站错误引起的定位失败", Toast.LENGTH_SHORT).show();
                break;
            case TencentLocation.ERROR_WGS84:
                Toast.makeText(BaseApp.getContext(), "无法将WGS84坐标转换成GCJ-02坐标时的定位失败", Toast.LENGTH_SHORT).show();
                break;
            case TencentLocation.ERROR_UNKNOWN:
                Toast.makeText(BaseApp.getContext(), "未知原因引起的定位失败", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mOnLocationChangedListener = onLocationChangedListener;
        //开启定位
        int err = mLocationManager.requestLocationUpdates(
                locationRequest, this, Looper.myLooper());
        switch (err) {
            case 1:
                Toast.makeText(this,
                        "设备缺少使用腾讯定位服务需要的基本条件",
                        Toast.LENGTH_SHORT).show();
                break;
            case 2:
                Toast.makeText(this,
                        "manifest 中配置的 key 不正确", Toast.LENGTH_SHORT).show();
                break;
            case 3:
                Toast.makeText(this,
                        "自动加载libtencentloc.so失败", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    @Override
    public void deactivate() {
        mLocationManager.removeUpdates(this);
        mLocationManager = null;
        locationRequest = null;
        mOnLocationChangedListener = null;
    }

    /**
     * 获取当前屏幕旋转角度
     *
     * @param context
     * @return 0表示是竖屏; 90表示是左横屏; 180表示是反向竖屏; 270表示是右横屏
     */
    public static int getScreenRotationOnPhone(Context context) {

        final Display display = ((WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

        switch (display.getRotation()) {
            case Surface.ROTATION_0:
                return 0;

            case Surface.ROTATION_90:
                return 90;

            case Surface.ROTATION_180:
                return 180;

            case Surface.ROTATION_270:
                return -90;
        }
        return 0;
    }

    //方向传感器
    @Override
    public void onSensorChanged(SensorEvent event) {
        //    Log.d(TAG,"*******************");
        float mAngle = 0.0f;
        long lastTime = 0;

        if (System.currentTimeMillis() - lastTime < TIME_SENSOR) {
            Log.d(TAG, "//////////////////////////////");
            return;
        }
        switch (event.sensor.getType()) {
            case Sensor.TYPE_ORIENTATION: {
                float x = event.values[0];
                x += getScreenRotationOnPhone(BaseApp.getContext());
                x %= 360.0F;
                if (x > 180.0F)
                    x -= 360.0F;
                else if (x < -180.0F)
                    x += 360.0F;

                if (Math.abs(mAngle - x) < 3.0f) {
                    break;
                }
                mAngle = Float.isNaN(x) ? 0 : x;
                if (pointerMarker != null) {
                    pointerMarker.setRotation(mAngle - 270);
                }
                lastTime = System.currentTimeMillis();
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }


    //开始导航按钮的点击函数
    public void navigation(View view) {
        useTencentNaviApp("北京仓");
        /*initDialog();
        carMarker.remove();

        pointerMarker = tencentMap.addMarker(new MarkerOptions(car_Location)
                .anchor(0.5f, 0.5f)
                .viewInfoWindow(true)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.pointer))
                .flat(true)
                .clockwise(false)
                .draggable(true));// 设置默认显示一个infowinfow

        isNavigation = true;
        ll_navigation.setVisibility(View.GONE);
        imgbtn_location.setVisibility(View.VISIBLE);
        CameraUpdate cameraSigma =
                CameraUpdateFactory.newCameraPosition(new CameraPosition(
                        new LatLng(car_Location), //中心点坐标，地图目标经纬度
                        17,  //目标缩放级别
                        0f, //目标倾斜角[0.0 ~ 45.0] (垂直地图时为0)
                        0f)); //目标旋转角 0~360° (正北方为0)
        tencentMap.moveCamera(cameraSigma);
        sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_FASTEST);
*/


    }


    //定位按钮的点击函数
    public void location(View view) {
        tencentMap.moveCamera(CameraUpdateFactory.newLatLng(car_Location));
        tencentMap.setMaxZoomLevel(17);
    }

    //自定义Marker的信息窗口-- 老板视角，查看货车司机位置
    public void setInofoView(boolean changed) {
        tencentMap.setInfoWindowAdapter(new TencentMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(final Marker marker) {
                //创建无边框自定义View
                return null;
            }

            @Override
            public View getInfoContents(final Marker marker) {
                if (changed) {
                    //创建带边框自定义View
                    View view = View.inflate(MapActivity.this, R.layout.custom_infowindow, null);
                    TextView tv1 = view.findViewById(R.id.tv1_name);
                    TextView tv2 = view.findViewById(R.id.tv2_content);
                    TextView tv3 = view.findViewById(R.id.tv3_location);

                    String phoneNum = "13312545125";
                    tv1.setText("李师傅");
                    tv2.setText("电话" + phoneNum);
                    tv3.setText("目前位于河北省北京市四合院1号");
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            callPhone(phoneNum);
                        }//跳转到打电话
                    });
                    return view;
                } else {
                    View view = View.inflate(MapActivity.this, R.layout.custome_infowindow2, null);
                    TextView tv1 = view.findViewById(R.id.tv1_title);
                    TextView tv2 = view.findViewById(R.id.tv2_content);

                    tv1.setText("北京四合院仓库");
                    tv2.setText("北京市四合院东巷三街15号楼");
                    return view;
                }

            }
        });

        tencentMap.setOnInfoWindowClickListener(new TencentMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                if (marker == marker1) {
                    //
                }
            }

            //  windowWidth - InfoWindow的宽度
            //windowHigh - InfoWindow的高度
            // x - 点击点在InfoWindow的x坐标点
            //y - 点击点在InfoWindow的y坐标点
            @Override
            public void onInfoWindowClickLocation(int width, int height, int x, int y) {
                Log.i("TAG", "当InfoWindow点击时，点击点的回调");
            }
        });
    }

    //弹窗提示是否打开定位
    private void initDialog() {
        //如果没有打开定位，则弹出提示窗
        if (!checkGPSIsOpen()) {
            final MyDialog dialog = new MyDialog(MapActivity.this);
            dialog.setMessage("请点击确定打开定位以便提高定位的准确度")
                    .setTitle("提示")
                    .setSingle(true).setOnClickBottomListener(new MyDialog.OnClickBottomListener() {
                        @Override
                        public void onPositiveClick() {//点击确定
                            dialog.dismiss();
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, GPS_REQUEST_CODE);
                        }

                        @Override
                        public void onNegativeClick() {
                            dialog.dismiss();
                        }


                    }).show();
        }

    }

    /**
     * 检测GPS是否打开
     *
     * @return
     */
    private boolean checkGPSIsOpen() {
        boolean isOpen;
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return isOpen;
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */

    public void callPhone(String phoneNum) {

        Intent intent = new Intent(Intent.ACTION_DIAL);

        Uri data = Uri.parse("tel:" + phoneNum);

        intent.setData(data);

        startActivity(intent);

    }


    //调用腾讯地图app导航
    public void useTencentNaviApp(String toName) {

        try {
            Uri uri = Uri.parse("qqmap://map/routeplan?type=drive&to=" + toName +
                    "&fromcoord=" + car_Location.getLatitude() + "," + car_Location.getLongitude() +

                    "&tocoord=" + toLatLng.getLatitude() + "," + toLatLng.getLongitude() + "&referer=AQGBZ-O5QRW-OOIRY-OG4JJ-KWV37-KWFNP");
            Intent intent = new Intent();
            intent.setData(uri);
            this.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "请安装腾讯地图", Toast.LENGTH_SHORT).show();
        }
    }


}
